package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.ClientMapper;
import com.ruan.mapper.ProjectMapper;
import com.ruan.pojo.*;
import com.ruan.service.ClientService;
import com.ruan.service.EmployeeService;
import com.ruan.service.ProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/client")
@Api(tags = "客户相关接口")//反映在swagger(运行之后访问http://localhost:8080/doc.html#/home)文档
public class ClientController {
    @Autowired
    private ClientService clientService;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private EmployeeService employeeService;


    @GetMapping("/exportToExcel")
    public ResponseEntity<byte[]> exportToExcel(){
        try {
            byte[] excelBytes = clientService.exportToExcel();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "客户表.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    //客户信息分页查询
    //创建一个controller方法，接收页面发送的请求并且接收参数（page,pageSize,name）
    @PostMapping("/page/{currentPage}/{pageSize}")
    @ApiOperation(value = "客户分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页码", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "queryEmployeeCondition", value = "客户查询条件", required = false, paramType = "body", dataType = "QueryEmployeeCondition")
    })
    //需要确保 queryEmployeeCondition 不为 null，否则在生成键时会导致 NullPointerException。
    // 可以使用 #queryEmployeeCondition?.name 和其他属性来避免这种情况。
    @Cacheable(cacheNames = "clientCache",
            key = "#currentPage + '-' " +
            "+ #pageSize " + "+ '-' " +
            "+ #queryEmployeeCondition?.name + '-' " +
            "+ #queryEmployeeCondition?.companyName + '-' " +
            "+ #queryEmployeeCondition?.status",
            unless = "#result == null")//缓存某些空结果
    public Result page(@PathVariable int currentPage,
                       @PathVariable int pageSize,
                       @RequestBody QueryEmployeeCondition queryEmployeeCondition){
//        System.out.println("client的page传来的参数是："
//                +currentPage+pageSize+queryEmployeeCondition);

        Page<Client> iPage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(queryEmployeeCondition.getName()!=null,
                Client::getName,queryEmployeeCondition.getName());
        queryWrapper.like(queryEmployeeCondition.getCompanyName()!=null,
                Client::getCompanyName,queryEmployeeCondition.getCompanyName());
        //!!!!!!!!!!!!!!!!!!
        queryWrapper.eq(!queryEmployeeCondition.getStatus().equals(""),
                Client::getStatus,queryEmployeeCondition.getStatus());
        //实现在指定条件下进行客户信息的分页查询。

        List<Client> clientList = clientMapper.selectList(queryWrapper);
        List<Client> updatedClientList = new ArrayList<>();
        //能查到未完成的项目就是合作中
        for(Client client : clientList){
//            System.out.println("client是"+client);
            LambdaQueryWrapper<Project> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Project::getClientId,client.getId());
            List<Project> projectList = projectMapper.selectList(queryWrapper1);

            boolean isOnGoing = false;
        if(!projectList.isEmpty()){
            for (Project project : projectList) {
//                System.out.println("有正在进行的项目吗："+project.getCompletionStatus()+"对比"+"onGoing");
              if(project.getCompletionStatus()!=null){
                if (project.getCompletionStatus().equals(Project.CompletionStatus.onGoing)){
//                    System.out.println("进来了吗");
                    isOnGoing = true;
                    break;
                }
              }
            }
        }
//            System.out.println("isOnGoing是"+isOnGoing);
            if (isOnGoing) {
                client.setStatus(1);//合作中
                clientMapper.updateById(client);//纠正数据库
//                System.out.println("客户状态变化了吗"+client.getStatus());
            } else {
                client.setStatus(0);//未合作
                clientMapper.updateById(client);//纠正数据库
            }

//          for(Project project : projectList){
////            if(project!=null){
//              System.out.println("有正在进行的项目吗："+project.getCompletionStatus());
//              if(project.getCompletionStatus().equals("onGoing")){//正在进行的项目
//                System.out.println("project是"+project);
//                client.setStatus(1);//合作中
//                System.out.println("状态变化了吗"+client.getStatus());
//                clientMapper.updateById(client);//纠正合作状态更新到数据库
//            }
//          }
            updatedClientList.add(client);
        }
        //不生效???应该到项目添加页操作
        System.out.println("返回多少条client："+updatedClientList);
        clientService.page(iPage,queryWrapper);

//        // 设置分页结果
//        iPage.setRecords(updatedClientList); // 确保 iPage 中包含更新后的客户列表

        return new Result(Code.SELECT_OK,iPage);
    }

    @PostMapping("/updateClient")
    @CacheEvict(value = "clientCache", allEntries = true)//表示要清理clientCache下面所有的缓存数据
    @ApiOperation(value = "修改客户接口")//反映在swagger(运行之后访问http://localhost:8080/doc.html#/home)文档
    public Result updateClient(@RequestBody Client client){
        if (clientService.updateById(client)){
            return new Result(Code.UPDATE_OK,"客户信息修改成功！");
        }
        return new Result(Code.UPDATE_ERR,"客户信息修改失败！");
    }

    @GetMapping("/deleteClient/{id}")
    @CacheEvict(value = "clientCache", allEntries = true)//表示要清理clientCache下面所有的缓存数据
    @ApiOperation(value = "删除客户接口")//反映在swagger(运行之后访问http://localhost:8080/doc.html#/home)文档
    public Result deleteClient(@PathVariable Integer id){
        System.out.println("deleteClient传来的id是"+id);

        if (clientMapper.deleteById(id) > 0){
            return new Result(Code.UPDATE_OK,"客户删除成功！");
        }
        return new Result(Code.UPDATE_ERR,"客户删除失败！");
    }

    //新增客户
    @PostMapping("/addClient")
    @CacheEvict(value = "clientCache", key = "#client.id")//精准删除缓存，key: setmealCache::#setmealDTO.categoryId
    @ApiOperation(value = "新增客户接口")//反映在swagger(运行之后访问http://localhost:8080/doc.html#/home)文档
    public Result save(@RequestBody Client client){
        System.out.println("新增客户，客户信息是："+client);
        clientService.save(client);//把这个对象存进去

        // 获取自增的client_id
        Long clientId = client.getId();

        // 构建包含client_id和成功消息的返回对象
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("client_id", clientId);
        responseData.put("message", "新增客户成功");

//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
//        return new Result(Code.SAVE_OK,"新增客户成功");
        return new Result(Code.SAVE_OK, responseData,"新增客户成功");
    }



    @GetMapping("/getCname")
    public Result getAllClientName(){
        log.info("查询所有的客户的名字信息");
        // 从数据库中检索所有客户的名字
//        List<String> clientNames = clientService.getAllClientNames();
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Client::getName,Client::getId);
        List<Client> clientNames = clientService.list(queryWrapper);

        System.out.println("客户名有"+clientNames);
//        return clients.stream().map(Client::getCname).collect(Collectors.toList())
        if(clientNames!=null){//查出来才返回@PathVariable Long id
            return new Result(Code.SELECT_OK,clientNames,"客户查询成功");
        }
        return new Result(Code.SELECT_ERR,"客户为空");
    }
}
